package com.zlx.store.user.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class IpInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private List<String> tokenList;
    private List<String> blockList;

    /**
     * ip拦截器，顺序在jwt验证之后，存入redis记录ip，用户jwt和请求次数，当该ip使用同一个jwt10秒内发出100个请求以上将被判定为机器人，拉入黑名单5分钟
     * 下次进入将判定blacklist中有无该用户jwt，如果有则返回ttl提醒还有多少时间封锁过期
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ipAddress = request.getRemoteAddr();
        String token = request.getHeader("token");
        Object o = redisTemplate.opsForValue().get("blockList");
        if (Objects.nonNull(o)) {
            blockList = (List<String>) o;
            if (blockList.stream().anyMatch(token::equals)) {
                return false;//这里应该抛出自定义异常用户拉入黑名单还有多久能够放出
            }
        }
        if (Objects.nonNull(redisTemplate.opsForValue().get(ipAddress))) {
            List<String> jwtList = (List<String>) redisTemplate.opsForValue().get(ipAddress);
            List<String> collect = jwtList.stream().filter(token::equals).collect(Collectors.toList());
            if (collect.size() > 100) {
                blockList.add(token);
                redisTemplate.opsForValue().set("blockList", blockList, 1000 * 60 * 5);
            }
        }
        tokenList.add(token);
        redisTemplate.opsForValue().set(ipAddress, tokenList, 10000);
        return true;
    }
}
